package vip.meeet.concurrent;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ThreadLocalTest4 {
    
    private static final ThreadLocal<SimpleDateFormat> threadLocal = new ThreadLocal<SimpleDateFormat>();
    
    static CountDownLatch latch = new CountDownLatch(1000);
    
    static LinkedList<Integer> done = new LinkedList<Integer>();
    
    static List<Integer> synchronizedList = Collections.synchronizedList(done);
    
    static class ParseDate implements Runnable{

        int i = 0;
        public ParseDate(int i) {
            this.i = i;
        }
        @Override
        public void run() {
            try {
                SimpleDateFormat sdf = threadLocal.get();
                if(sdf == null){
                    sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    threadLocal.set(sdf);
                }
                Date t = sdf.parse("2017-04-20 9:10:"+i%60);
                System.out.println(i+":"+t);
            } catch (ParseException e) {
                e.printStackTrace();
            }finally{
                latch.countDown();
            }
//            done.add(i);
            synchronizedList.add(i);
        }
        
    }
    
    public static void main(String[] args) {
        ExecutorService pool = Executors.newFixedThreadPool(10);
        for(int i=0;i<1000;i++){
            pool.submit(new ParseDate(i));
        }
        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        pool.shutdownNow();
        System.out.println(done.size());
        Collections.sort(done);
        System.out.println(done);
    }

}
